<?php

namespace app\index\controller;

use think\Controller;
use think\Facade\Request;
use app\index\model\Driver as Model;
use app\index\validate\Driver as Validate;
use app\index\model\Warehouse;
use PHPExcel_IOFactory;
use PHPExcel;
use PHPExcel_Shared_Date;
class Driver extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if(Request::isPost()){
            $where='';
            $nickname= input('post.nickname');
            $warehouse = Request::post('warehouse');
            if($warehouse)
            {
                $where['warehouse'] = $warehouse;
            }
            if($nickname!=''){
                $where[] = ['nickname', 'like', "%{$nickname}%"];
            }
            $order = Model::where($where)->order('id desc')->paginate(10);
            $total= Model::where($where)->order('id desc')->count();
            $data = $order->items();
            returnAjax('200',[
                'data'=>$data,
                'total'=>$total,
                'page'=>input('get.page',1)
            ]);
        }
        $wareHouse = Warehouse::all();
        return $this->fetch('',['wareHouse'=>$wareHouse]);
    }

  public function warehouseItmes()
  {

          $warehouse = Request::post('warehouse');
          $where['warehouse'] = $warehouse;
          $order = Model::where($where)->order('id desc')->select();
          returnAjax('200',[
              'data'=>$order->toArray()
          ]);
  }

    public function create()
    {
           $wareHouse = Warehouse::all();
           return $this->fetch('',['wareHouse'=>$wareHouse]);
    }
    public function save()
    {
              if(Request::isPost())
              {
                  $post = Request::post();
                  $validate = new Validate();
                  if (!$validate->check($post)) {
                      returnAjax('201',$validate->getError());
                  }
                  if( Model::isRepeatDeriverId($post['driver_id']) )
                  {
                      returnAjax('201','司机id已存在');
                  }
                  $latAndLng = $this->getLatlng( $post['address'] );  //获取经纬度
                  if( $latAndLng['lat']==0 )
                  {
                      returnAjax('201','读取经纬度失败');
                  }
                  $post['lat'] = $latAndLng['lat'];
                  $post['lng'] = $latAndLng['lng'];
                  $res = Model::create($post);
                  if( $res )
                  {
                      returnAjax('200','添加成功');
                  }
                  returnAjax('201','添加失败');

              }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read()
    {
        $id = Request::get('id');
        $data = Model::where(['id'=>$id])->find();
        $wareHouse = Warehouse::all();
        return $this->fetch('driver/update',['data'=>$data,'wareHouse'=>$wareHouse]);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        if(Request::isPost())
        {
            $post = Request::post();
            $validate = new Validate();
            $result =  $this->validate($post,'app\index\validate\Driver.edit');
            if (!$result) {
                returnAjax('201',$result);
            }
            $latAndLng = $this->getLatlng( $post['address'] );  //获取经纬度
            if( $latAndLng['lat']==0 )
            {
                returnAjax('201','读取经纬度失败');
            }
            $post['lat'] = $latAndLng['lat'];
            $post['lng'] = $latAndLng['lng'];
            $res = Model::update($post);
            if( $res )
            {
                returnAjax('200','修改成功');
            }
            returnAjax('201','修改失败');

        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 显示分配司机页面
     * @return mixed
     */
    public function assignVehicle()
    {
       return $this->fetch('driver/assign');
    }

    /**
     *
     * 保存分配司机
     * @return mixed
     */
    public function saveAssignVehicle()
    {
         if(Request::isPost())
         {
             $post  = Request::post();
             if(Model::vehicleIsAssigned( $post['driver_id'] , $post['vehicle_id']))
             {
                 returnAjax('201','车辆已经被分配了');
             }
             $res = Model::where(['driver_id'=>$post['driver_id']])->update(['vehicle_id'=>$post['vehicle_id']]);
             if($res)
             {
                 returnAjax('200','设置成功');
             }
             returnAjax('201','设置失败');
         }
    }
    /**
     *
     * 取消分配司机
     * @return mixed
     */
    public function cancleAssignVehicle()
    {
        if(Request::isPost())
        {
            $post  = Request::post();
            $res = Model::where(['driver_id'=>$post['driver_id']])->update(['vehicle_id'=>null]);
            if($res)
            {
                returnAjax('200','取消成功');
            }
            returnAjax('201','取消失败');
        }
    }

    /**
     * 显示批量修改页面
     * @return mixed
     */
    public function showUpdateMult()
    {
        return $this->fetch('update_mult');
    }
    /**
     * 显示批量修改页面
     * @return mixed
     */
    public function updateMult()
    {
        if(Request::isPost()){
            $objPHPExcel = \PHPExcel_IOFactory::load($this->getUploadExcle());
            $objPHPExcel->setActiveSheetIndex(0);
            $driver=[];
            $i=1;
            $start = time();
            while (true){
                $i++;
                $driver['nickname'] = $objPHPExcel->getActiveSheet()->getCell("A{$i}")->getValue();
                $driver['driver_id'] = $objPHPExcel->getActiveSheet()->getCell("B{$i}")->getValue();
                $driver['vehicle_id'] = $objPHPExcel->getActiveSheet()->getCell("C{$i}")->getValue();
                $driver['start_location'] = $objPHPExcel->getActiveSheet()->getCell("D{$i}")->getValue();
                $driver['end_location'] = $objPHPExcel->getActiveSheet()->getCell("E{$i}")->getValue();
                $driver['departure_time'] =$this->_formateTime( $objPHPExcel->getActiveSheet()->getCell("F{$i}")->getValue() );
                $driver['end_time'] =$this->_formateTime( $objPHPExcel->getActiveSheet()->getCell("G{$i}")->getValue() );

                $driver['work_hours'] = $objPHPExcel->getActiveSheet()->getCell("H{$i}")->getValue();
                $driver['address'] = $objPHPExcel->getActiveSheet()->getCell("I{$i}")->getValue();
                $driver['phone'] = $objPHPExcel->getActiveSheet()->getCell("J{$i}")->getValue();
                $latAndLng = $this->getLatlng($driver['address']);
                $driver['lat'] = $latAndLng['lat'];
                $driver['lng'] = $latAndLng['lng'];
                if(!$driver['driver_id']) break;
                Model::where(['driver_id'=>$driver['driver_id']])->update($driver);
            }
            returnAjax('200','SUCCESS');
        }
    }
    /**获取上传文件
     * @return string
     */
    public function getUploadExcle(){
        $file = request()->file('file');
        $info = $file->move( '../uploads');
        if($info){
            return $uploadFile = "../uploads/".$info->getSaveName();
        }else{
            exit($file->getError());
        }
    }

    /**
     * 格式化从excel表格里面获取的时间
     * @param $excleTime excel表格时间
     * @return false|string
     */
    private function _formateTime($excleTime)
    {
        $excleTime = 25569 + $excleTime;
        $time = ($excleTime - 25569) * 24*60*60;
        return gmdate('H:i', ceil( $time ));
    }
}
